﻿using Inovout.Data.Service;
using KuaJing.Common.Domain;
using KuaJing.Customs.Domain;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace KuaJing.Customs.Service
{
    public class DeclarationService : RepositoryService<Declaration>
    {
        private IRepositoryService<File> fileService;
        public DeclarationService(IRepositoryService<File> fileService)
        {
            this.fileService = fileService;
        }
        public IEnumerable<Declaration> Import(IEnumerable<string> files)
        {
            List<Declaration> declarations = new List<Declaration>();
            foreach (var file in files)
            {
                try
                {
                    declarations.Add(Import(file));
                }
                catch (NotSupportedException ex)
                {
                    log.Error(ex);
                }
            }
            return declarations;
        }
        public Declaration Import(string fileName)
        {
            //JKJ16001828E大东玩具
            var declarationParser = new DeclarationParser();
            var parsedDeclaration = declarationParser.Parse(fileName);
            var declaration = Query().SingleOrDefault(d => d.Code == parsedDeclaration.Code);
            if (declaration == null)
            {
                declaration = parsedDeclaration;
                declaration.File = new File()
                {
                    Name = fileName,
                    Type = typeof(Declaration).Name
                };
                Save(declaration);
            }
            return declaration;
        }
    }
}
